package com.wanjia.bpsapi.crontab;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wanjia.bpsapi.pojo.entity.WjProductOffer;
import com.wanjia.bpsapi.properties.TimedTaskProperties;
import com.wanjia.bpsapi.service.IWjProductOfferService;
import com.wanjia.bpsapi.service.IWjSupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;

@Component
@Slf4j
public class TimedTaskVegePrice {

    @Autowired
    TimedTaskProperties timedTaskProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    IWjProductOfferService wjProductOfferService;

    @Autowired
    IWjSupplierService wjSupplierService;

    public void run(){
        wjProductOfferService.remove(new QueryWrapper<>());
        log.info("根据基地获取菜品报价定时任务执行中...");
        List<String> baseID = wjSupplierService.getID();
        for (String o : baseID) {
            String VegePriceUrl = timedTaskProperties.getVegePriceUrl();
            String URL=VegePriceUrl+"?supplier_id="+o+"&page=0&limit=9999999";
            HttpHeaders headers = new HttpHeaders();
            headers.add("Token", timedTaskProperties.getToken());
            HttpEntity<String> entity = new HttpEntity<>(headers);
            ResponseEntity<String> response= restTemplate.exchange(URL, HttpMethod.GET, entity,String.class);
            String body = response.getBody();
            JSONObject jb = JSONObject.parseObject(body);
            JSONArray data = jb.getJSONObject("data").getJSONArray("data");
            for (int i = 0; i < data.size(); i++) {
                JSONObject object = data.getJSONObject(i);
                WjProductOffer wjProductOffer = JSON.parseObject(String.valueOf(object), WjProductOffer.class);
                //获取商品规格里面价格，库存，单位字段
                String suks = wjProductOffer.getSuks();
                JSONObject jsonObject = JSON.parseArray(suks).getJSONObject(0);
                String price = jsonObject.getString("price");
                BigDecimal bd = new BigDecimal(price);
                wjProductOffer.setPrice(bd);
                String suk = jsonObject.getString("suk");
                wjProductOffer.setSuk(suk);
                String stock = jsonObject.getString("stock");
                wjProductOffer.setStock(Long.parseLong(stock));
                wjProductOfferService.addProductOffer(wjProductOffer);
            }
        }

    }
}
